package com.rjkj.medicalwaste.base

import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.TextView
import androidx.activity.addCallback
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.google.android.material.snackbar.Snackbar
import com.mpaas.aar.demo.custom.ScanHelper
import com.rjkj.medicalwaste.MainActivity
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.bean.CodeType
import com.rjkj.medicalwaste.bean.GarbageStatus
import com.rjkj.medicalwaste.livedatabus.LiveDataBus
import com.rjkj.medicalwaste.ui.home.WaitDialog
import com.rjkj.medicalwaste.viewmodels.UserViewModel

fun checkState(status: String): String {
    return when (status) {
        GarbageStatus.produce -> "生产"
        GarbageStatus.collect -> "收集"
        GarbageStatus.loading -> "入库"
        GarbageStatus.review -> "已复核"
        GarbageStatus.boxed -> "已装箱"
        GarbageStatus.outbound -> "出库"
        GarbageStatus.finished -> "结束"
        else -> "错误"
    }
}

abstract class BaseFragment<T : ViewDataBinding> : Fragment() {
    val TAG = "BaseFragment"

    /**
     * 需要被调用
     * @param binding T
     */
    abstract fun onSubscribeUi(binding: T)

    override fun onAttach(context: Context) {
        super.onAttach(context)
        requireActivity().onBackPressedDispatcher.addCallback(this) {
            showAreYouSureDialog()
        }

    }

    fun initKeyEvent() {
        LiveDataBus.get().with(MainActivity.KEY_DATA, Boolean::class.java).observe(
            viewLifecycleOwner, {
                scanWithCustomUI()
            }
        )
    }

    open fun showAreYouSureDialog() {
        findNavController().navigateUp()
    }

    fun showTip(message: String) {
        if (TextUtils.isEmpty(message)) {
            return
        }
        Snackbar.make(requireView(), message, Snackbar.LENGTH_LONG).apply {
            view.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.black_grey))
            view.findViewById<TextView>(com.google.android.material.R.id.snackbar_text).also {
                it.textSize = 28f
                it.setTextColor(Color.WHITE)
            }
        }.show()
    }

    fun scanWithCustomUI() {
        ScanHelper.getInstance().scan(requireContext(),
            ScanHelper.ScanCallback { isProcessed, result ->
                if (!isProcessed) {
                    // 扫码界面点击物理返回键或左上角返回键
                    return@ScanCallback
                }
                if (result == null || result.data == null) {
                    return@ScanCallback
                }
                dealCustomScanData(result.data.toString())


            })
    }

    open fun dealCustomScanData(data: String) {

    }

    /**
     * 初始化提示SnackBar注册
     * @param viewModel BaseViewModel
     */
    open fun initTip(viewModel: BaseViewModel) {
        viewModel.tips.observe(viewLifecycleOwner, {
            it?.let {
                showTip(it)
                viewModel.onSnackBarShown()
            }
        })
    }

    open fun initDialog(viewModel: UserViewModel) {
        viewModel.uploadEvent.observe(viewLifecycleOwner) {
            Log.e(TAG, "Dialog: $it")
            if (it) {
                val waitDialog: WaitDialog = WaitDialog().apply {
                    setStyle(DialogFragment.STYLE_NORMAL, R.style.dialogNormal)//添加上面创建的style
                }
                if (!waitDialog.isResumed) {
                    waitDialog.show(parentFragmentManager, "waitDialog")
                }

            }

        }
    }

    fun isExit() {
        AlertDialog.Builder(requireContext()).setTitle("是否退出")
            .setNegativeButton("取消") { _: DialogInterface, _: Int ->
            }
            .setPositiveButton("确定") { _: DialogInterface, _: Int ->
                lifecycleScope.launchWhenResumed {
                    findNavController().navigateUp()
                }
            }
            .show()
    }

    /**
     * 扫码的类型
     * @param code String
     * @return CodeType
     */
    fun checkCode(code: String): CodeType {
        if (code.length == 15) {
            code.substring(10, 12).also {
                when (it) {
                    CodeType.Cleaner.string -> {
                        return CodeType.Cleaner
                    }
                    CodeType.Department.string -> {
                        return CodeType.Department
                    }
                    CodeType.Nurser.string -> {
                        return CodeType.Nurser
                    }
                    CodeType.Recycle.string -> {
                        return CodeType.Recycle
                    }
                    CodeType.StagingRoom.string -> {
                        return CodeType.StagingRoom
                    }
                }
            }
        }
        return CodeType.Other
    }
}